package com.dingpeikeji.quickdeer.modules.utils;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import com.google.common.collect.Lists;

public class ValidateCodeTool {
	
	public static final String VALIDATE_FROM_PHONE = "validateCodeFromPhone";

	public static List<String> validateFromPhone(HttpServletRequest request, String validateCode, String type) {
		List<String> messages = Lists.newArrayList();
		@SuppressWarnings("unchecked")
		Map<String,Object> map = (Map<String,Object>)request.getSession().getAttribute("registercode");
		if(map == null) {
			messages.add("验证码错误");
		} else  if(StringUtils.isEmpty(validateCode)) {
			messages.add("验证码为空");	
		} else {
			Long time = (Long) map.get("time"); // 时间毫秒数
			Date date = new Date();
			Long wait = 60*1000L; // 验证码等待毫秒数
			if(time+wait<date.getTime()) {
				messages.add("验证码超时，请重新发送");
			} else {
				String code = (String) map.get("code");
				if(!validateCode.equals(code)) {
					messages.add("验证码不正确");
				}
			}
		}
		return messages;
	}
	
	// 生成验证码内容
	public static String genCode() {
		String chars = "0123456789";
		char[] rands = new char[4];
		for (int i = 0; i < 4; i++) {
			int rand = (int) (Math.random() * 10);
			rands[i] = chars.charAt(rand);
		}
		return new String(rands);
	}
}
